import axios, { AxiosError } from 'axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/user';

export const baseURL = 'http://syt.atguigu.cn/api';
// export const baseURL = '/api';

const request = axios.create({
	timeout: 5000,
	baseURL,
});

request.interceptors.request.use((config) => {
	const userStore = useUserStore();

	if (userStore.userInfo.token) {
		config.headers.token = userStore.userInfo.token;
	}

	return config;
});

request.interceptors.response.use(
	(response) => {
		return response.data;
	},
	(error: AxiosError) => {
		const status = error.response?.status;

		switch (status) {
			case 404:
				ElMessage.error(error.message);
				break;
		}

		return Promise.reject(error);
	}
);

export default request;
